<?php

namespace app\controllers;

use app\librarys\BaseController;
use app\models\Menu;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\librarys\Tools;

class SiteController extends BaseController
{
    public $layout = true;
    public $enableCsrfValidation = false;


    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->redirect('/site/login');
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        //Yii::$app->session->remove("session_key_manager");//session_key_manager
        //Yii::$app->user->logout();

        //return $this->goHome();
    }

    public function actionSignout()
    {
        Yii::$app->session->removeAll();
        return $this->redirect(Tools::urlBase() . "/site/login");
    }

    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    public function actionAbout(){
        return $this->render('about');
    }

    /**
     * 登录
     * @return string|\yii\web\Response
     */
    public function actionLogin()
    {
        $this->layout = false;
        $model = new LoginForm();
        $post = \Yii::$app->request->post();
        $return_url = \Yii::$app->request->get('return_url');
        $post['init'] = isset($post['init']) ? $post['init'] : 1;
        //$post['LoginForm']['rememberMe'] = isset($post['LoginForm']['rememberMe']) && $post['LoginForm']['rememberMe'] == 'on' ? true : false;

        $manager = null;
        if ($model->load($post) && $model->login($manager)) {     //$model->load($post) && $model->login()

            if ($return_url) {
                $url = $return_url;
            } else {
                $url = Tools::urlBase();
                $menus = Menu::getAllMenus();

                foreach ($menus as $menu) {
                    if (!$menu['parent_id'] && isset($menu['sub_menu_list'])) {
                        $url = Menu::getUrlForInit($menu, $url);
                        break;
                    }
                }
            }
            return $this->redirect($url);
        }
        return $this->render('login', [
            'model' => $model,
            'post' => $post,
            'return_url' => $return_url
        ]);
    }

}
